using System;
using System.IO;
using Microsoft.Coding4Fun.TweetCraft.Tests.Support.Mocks;
using Microsoft.Coding4Fun.TweetCraft.Tray.Support;
using NUnit.Framework;

namespace Microsoft.Coding4Fun.TweetCraft.Tests.Support
{
	[TestFixture]
	public class UpdateManagerTest
	{
		private readonly Uri serverUri = new Uri("http://localhost/mock/version.text");
		private MockDownloadManager downloadManager;
		private UpdateManager updateManager;
		private static string TestContentDownloadString = String.Empty;

		#region SetUp

		[SetUp]
		public void SetUp()
		{
			downloadManager = new MockDownloadManager(TestContentDownloadString);
			updateManager = new UpdateManager(downloadManager, serverUri);
		}

		#endregion

		#region TearDown

		[TearDown]
		public void TearDown()
		{
			downloadManager.Dispose();
		}

		#endregion

		#region Tests

		[Test(Description = "")]
		public void TestDownloadVersionFileSuccess()
		{
			TestContentDownloadString = "1.1.0";
			downloadManager.ContentToDownload = TestContentDownloadString;
			updateManager.CheckForApplicationUpdates(result =>
			                                         	{
															Assert.IsTrue(result.Success);
															Assert.IsTrue(result.UpdateAvailable);
															Assert.AreEqual(1, result.ServerVersion.Major);
															Assert.AreEqual(1, result.ServerVersion.Minor);
			                                         	});
		}

		[Test(Description = "")]
		public void TestDownloadVersionFileUpdateNotAvailable()
		{
			TestContentDownloadString = "0.1.0";
			downloadManager.ContentToDownload = TestContentDownloadString;
			updateManager.CheckForApplicationUpdates(result =>
			{
				Assert.IsTrue(result.Success);
				Assert.IsFalse(result.UpdateAvailable);
				Assert.AreEqual(0, result.ServerVersion.Major);
				Assert.AreEqual(1, result.ServerVersion.Minor);
			});
		}

		[Test(Description = "")]
		public void TestDownloadManagerSuccess()
		{
			TestContentDownloadString = "1.1.0";
			downloadManager.ContentToDownload = TestContentDownloadString;
			downloadManager.DownloadFile(serverUri, (content, ex) =>
														{
															Assert.IsNotNull(content);
															if (content.Position > 0)
																content.Position = 0;

															string contentString;
															using (var reader = new StreamReader(content))
															{
																contentString = reader.ReadToEnd();
															}
															Assert.IsNotNull(contentString);
															Console.WriteLine(contentString);
															Assert.AreEqual(TestContentDownloadString, contentString);
														});
		}

		#endregion


	}
}